package com.crcc.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient
 *
 * @author HongjianZ
 */
public class HttpClientUtil {
	// 创建CookieStore实例
	static CookieStore cookieStore = null;
	static HttpClientContext context = null;

	/**
	 * Get请求
	 *
	 * @param uri
	 * @return
	 */
	public static String GET(String uri) {
		String result = null;
		try {
			// 创建HttpClient实例
			CloseableHttpClient httpclient = HttpClients.createDefault();
			// 创建Get方法实例
			HttpGet httpgets = new HttpGet(uri);
			HttpResponse response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = convertStreamToString(entity.getContent());
				httpgets.abort();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * POST 表单数据
	 *
	 * @param uri
	 * @param param
	 */
	@SuppressWarnings("deprecation")
	public static String POST(String uri, Map<String, String> param) {
		@SuppressWarnings({ "resource" })
        DefaultHttpClient client = new DefaultHttpClient();
		StringBuilder sb = new StringBuilder();
		String line = "";
		HttpPost post = new HttpPost(uri);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			for (String key : param.keySet()) {
				nameValuePairs.add(new BasicNameValuePair(key, param.get(key)));
			}
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			while ((line = rd.readLine()) != null) {
				sb.append(line + "\n");
			}
			CookieStore cookieStore = client.getCookieStore();
			client.setCookieStore(cookieStore);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * POST JSON数据
	 * 
	 * @param uri
	 * @param jsonParam
	 * @return
	 */
	public static String POST(String uri, JSONObject jsonParam) {
		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;
		StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		try {
			HttpResponse resp = client.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity he = resp.getEntity();
				respContent = EntityUtils.toString(he, "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respContent;
	}

	/**
	 * POST 获取二维码图片
	 * 
	 * @param uri
	 * @param jsonParam
	 * @param file
	 * @param path
	 *            文件上传路径
	 * @return
	 */
	public static String POSTqrode(String uri, JSONObject jsonParam, String file, String path) {
		String fileName = file + ".jpg";
		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpClient client = HttpClients.createDefault();
		StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		try {
			HttpResponse resp = client.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity resEntity = resp.getEntity();
				if (resEntity != null) {
					InputStream instreams = resEntity.getContent();
					File f = new File(path);
					if (!f.exists()) {
						f.mkdirs();
						if (!OS.isWindows()) {
							Runtime.getRuntime().exec("chmod -R 777 " + path);
						}
					}
					UtilFile.copyInputStreamToFile(instreams, new File(path + fileName));
					if (!OS.isWindows()) {
						Runtime.getRuntime().exec("chmod -R 777 " + path + fileName);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileName;
	}

	/**
	 * POST JSON数据
	 * 
	 * @param uri
	 * @param jsonParam
	 * @return
	 */
	public static String POSTJson(String uri, String jsonParam) {
		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;
		StringEntity entity = new StringEntity(jsonParam, "utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		try {
			HttpResponse resp = client.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity he = resp.getEntity();
				respContent = EntityUtils.toString(he, "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respContent;
	}


	/**
	 * IO转换
	 *
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(HttpClientUtil.GET("http://api.map.baidu.com/weather/v1/?district_id=130322&data_type=all&ak=VXxuWjUuE5UoQOSIu6nqaiF7L0hmvGog"));
	}
}
